package com.jianyun.jyzs.utils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class AsyncTaskFmUtil extends AsyncTask<Object, Integer, HttpResultFmVO> {
	
	 // 可变长的输入参数，与AsyncTask.exucute()对应  
    public AsyncTaskFmUtil(){  
    }  
    // 可变长的输入参数，与AsyncTask.exucute()对应  
    public AsyncTaskFmUtil(Handler handler, String url, List<NameValuePair> params, Object param){
    }  

    @SuppressWarnings("unchecked")
	@Override  
    protected HttpResultFmVO doInBackground(Object... params) {
    	HttpResultFmVO res = new HttpResultFmVO();
		res.isNormal = false;
		res.mHandler = (Handler)params[0];
		if(params.length > 3){
			res.param = params[3];
		}
		try {
            HttpClient client = new DefaultHttpClient(); // 自己去初始化，通常会自己写一个DefaultHttpClient
            // 为Post设置一些头信息  
            HttpPost post = new HttpPost(String.valueOf(params[1]));
            if(params[2] instanceof MultipartEntity){
            	post.setEntity((MultipartEntity)params[2]);
            }else if(params[2] instanceof List){
            	post.setEntity(new UrlEncodedFormEntity((List<NameValuePair>)params[2], HTTP.UTF_8));
            }      
            // 请求超时
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			// 读取超时
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,20000);
              
            HttpResponse response = client.execute(post);
            /* 若状态码为200 ok */
			if(response.getStatusLine().getStatusCode() == 200){
				/* 读返回数据 */
				res.json = EntityUtils.toString(response.getEntity());
				res.isNormal = true;
			}else{
				res.err = "Error Response: "+ response.getStatusLine().toString();
			}
		} catch (ClientProtocolException e) {
			res.err = e.getMessage()==null?"请求异常!":e.getMessage().toString();
		} catch (IOException e) {
			res.err = e.getMessage()==null?"请求异常!":e.getMessage().toString();
		} catch (Exception e) {
			res.err = e.getMessage()==null?"请求异常!":e.getMessage().toString();
		}
        return res;
	}

    @Override  
    protected void onProgressUpdate(Integer... values) {  
    }  

    /** 
     * 在doInBackground 执行完成后，onPostExecute方法将被UI thread调用，后台的计算结果将通过该方法传递到UI thread. 
     */
    @Override  
    protected void onPostExecute(HttpResultFmVO result) {
    	try {
    		if(result.mHandler != null && result != null){
    			Message msg = new Message();
    			Bundle bundle = new Bundle();
    			bundle.putSerializable(SysConstant2.msg_key_parcelable, result);
    			msg.setData(bundle);
    			msg.what = result.what;
    			result.mHandler.sendMessage(msg);
    		}
		} catch (Exception e) {
    		e.printStackTrace();
		}
    }  

    @Override  
    protected void onCancelled() {  
    }  
	/** 
     * 该方法将在执行实际的后台操作前被UI thread调用。这个方法只是做一些准备工作，如在界面上显示一个进度条。 
     */  
    @Override  
    protected void onPreExecute() {  
    }  

}  